<template>
  <ul class="xitongYonghu" style="z-index: 1">
    <li class="xitongYonghu-top">
      <ul class="xitong-search" style="padding: 10px;display: flex;justify-content: space-between;align-items: center;">
        <div class="operation-group">
          <el-button type="primary" @click="dialogFormVisible = true">
            <el-icon><Plus /></el-icon>添加
          </el-button>
          <el-button type="danger" @click="deleteTick">
            <el-icon><Delete /></el-icon>勾选删除
          </el-button>
        </div>

        <div class="search-group">
          <el-select v-model="searchCourseTypeId" placeholder="选择音频类型" clearable>
            <el-option
              v-for="item in courseTypes"
              :key="item.courseTypeId"
              :label="item.courseTypeName"
              :value="item.courseTypeId"
            />
          </el-select>
          <el-input
            v-model="searchTitle"
            placeholder="搜索标题..."
            clearable
            style="width: 200px; margin-left: 10px"
          />
        </div>
        <el-button @click="serchBtn" style="margin-left: 10px">
          🔍搜索
        </el-button>
        <el-button @click="resetSerchbtn">
          重置
        </el-button>
      </ul>

      <!-- 添加音频对话框 -->
      <el-dialog v-model="dialogFormVisible" title="添加音频" width="500">
        <el-form :model="form2">
          <el-form-item label="音频文件" :label-width="formLabelWidth" required>
            <el-upload
                class="upload-demo"
                :auto-upload="false"
                ref="audioUploadRef"
                :on-change="handleAudioChange"
                :before-upload="beforeUpload"
                accept=".mp3,.wav,.ogg"
            >
              <el-button type="primary">选择音频文件</el-button>
              <template #tip>
                <div v-if="form2.filename" class="el-upload__tip">
                  已选择音频文件
                </div>
              </template>
            </el-upload>
          </el-form-item>
          <el-form-item label="封面图片" :label-width="formLabelWidth" required>
            <el-upload
                :auto-upload="false"
                ref="imageUploadRef"
                :on-change="handleImageChange"
                :before-upload="beforeUploadImg"
                :show-file-list="false"
                accept="image/*"
                class="avatar-uploader"
            >
              <div class="avatar-wrapper">
                <img v-if="form2.img" :src="form2.img" class="avatar" />
                <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                <div class="upload-tip">
                  图片大小不超过2M
                  <br>
                  仅支持PNG、JPEG、JPG类型图片
                  <br>
                  建议上传200*200或300*300尺寸的图片
                </div>
              </div>
            </el-upload>
          </el-form-item>
          <el-form-item label="标题" :label-width="formLabelWidth" required>
            <el-input v-model="form2.title" />
          </el-form-item>
          <el-form-item label="音频类型" :label-width="formLabelWidth">
            <el-select v-model="form2.courseTypeId">
              <el-option 
                v-for="item in courseTypes"
                :key="item.courseTypeId"
                :label="item.courseTypeName"
                :value="item.courseTypeId"
              />
            </el-select>
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取消</el-button>
            <el-button type="primary" @click="addFM">
              确认添加
            </el-button>
          </div>
        </template>
      </el-dialog>

      <!-- 修改音频对话框 -->
      <el-dialog v-model="xiugaiVisible" title="修改音频" width="500">
        <el-form :model="form2">
          <!-- 与添加表单相同的字段,但不包括文件上传 -->
          <el-form-item label="标题" :label-width="formLabelWidth" required>
            <el-input v-model="form2.title" />
          </el-form-item>
          <el-form-item label="音频类型" :label-width="formLabelWidth">
            <el-select v-model="form2.courseTypeId">
              <el-option 
                v-for="item in courseTypes"
                :key="item.courseTypeId"
                :label="item.courseTypeName"
                :value="item.courseTypeId"
              />
            </el-select>
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="xiugaiVisible = false">取消</el-button>
            <el-button type="primary" @click="EditFM">
              确认修改
            </el-button>
          </div>
        </template>
      </el-dialog>

      <!-- 音频播放对话框 -->
      <el-dialog
        v-model="audioPlayerVisible"
        :title="currentAudio.title"
        width="350px"
        @close="stopAudio"
        class="audio-dialog"
        :modal="false"
        :append-to-body="true"
        :draggable="true"
      >
        <div class="audio-player-container">
          <div class="audio-info">
            <el-image 
              v-if="currentAudio.img"
              :src="currentAudio.img"
              class="audio-cover"
              fit="cover"
            />
          </div>
          <audio
            ref="audioPlayer"
            :src="currentAudio.filename"
            controls
            style="width: 100%"
          >
            您的浏览器不支持音频播放
          </audio>
        </div>
      </el-dialog>
    </li>

    <!-- 音频列表 -->
    <li>
      <el-table v-if="isShow" :data="itemsArr" style="width: 100%" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="fmId" label="ID" width="80" />
        <el-table-column label="封面" width="100">
          <template #default="scope">
            <el-image 
              style="width: 50px; height: 50px"
              :src="scope.row.img"
              fit="cover"
            />
          </template>
        </el-table-column>
        <el-table-column prop="title" label="标题" width="200" />
        <el-table-column label="播放" width="100">
          <template #default="scope">
            <el-button
              size="small"
              type="primary"
              circle
              @click="playAudio(scope.row)"
              :title="'播放 ' + scope.row.title"
            >
              <el-icon><VideoPlay /></el-icon>
            </el-button>
          </template>
        </el-table-column>
        <el-table-column prop="courseTypeId" label="音频类型" width="120">
          <template #default="scope">
            {{ scope.row.courseTypeName }}
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="上传时间" width="950">
          <template #default="scope">
            {{ formatDateTime(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="用户操作" width="180" align="right" fixed="right">
          <template #default="scope">
            <div class="operation-buttons">
              <el-button size="small" @click="handleEdit(scope.row)">
                修改
              </el-button>
              <el-button
                  size="small"
                  type="danger"
                  @click="handleDelete(scope.row.fmId)"
              >
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </li>

    <!-- 分页器 -->
    <li>
      <el-pagination v-if="isShow"
                     @size-change="handleSizeChange"
                     @current-change="handleCurrentChange"
                     :current-page="currentPage"
                     :page-sizes="[3, 5, 10]"
                     :page-size="pageSize"
                     layout="total, sizes, prev, pager, next, jumper"
                     :total="total">
      </el-pagination>
    </li>
  </ul>
</template>

<script setup>
import { computed, ref, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'
import { Plus, Delete, VideoPlay } from '@element-plus/icons-vue'

const dialogFormVisible = ref(false)
const xiugaiVisible = ref(false)
const isShow = ref(true)
const searchAll = ref("")
const formLabelWidth = '140px'
const currentPage = ref(1)
const pageSize = ref(5)

// 表单数据
const form2 = ref({
  title: "",
  filename: "",
  img: "",
  courseTypeId: "",
})

// 音频列表数据
const fmList = ref([])
const courseTypes = ref([])
const total = ref(0)  // 添加总条数记录

// 搜索相关
const searchTitle = ref('')
const searchCourseTypeId = ref('')

// 获取音频列表
const getFMList = async () => {
  try {
    const response = await axios.get('admin/fm/page', {
      params: {
        page: currentPage.value,
        pageSize: pageSize.value
      }
    })
    if (response.data.code === 200) {
      console.log('分页数据:', response.data.data)
      fmList.value = response.data.data.list    // 修改为 list
      total.value = response.data.data.total    // 获取总条数
      // 更新当前页和每页大小
      currentPage.value = response.data.data.pageNum || currentPage.value
      pageSize.value = response.data.data.pageSize || pageSize.value
    } else {
      ElMessage.error('获取音频列表失败')
    }
  } catch (error) {
    console.error('获取音频列表失败:', error)
    ElMessage.error('获取音频列表失败')
  }
}

// 获取课程类型列表
const getCourseTypes = async () => {
  try {
    const response = await axios.get('admin/fm/courseType')
    if (response.data.code !== 200) {
      ElMessage.error('获取课程类型失败')
      return
    }
    console.log('课程类型数据:', response.data.data)
    courseTypes.value = response.data.data.map(item => ({
      courseTypeId: item.courseTypeId,
      courseTypeName: item.courseTypeName
    }))
  } catch (error) {
    console.error('获取课程类型失败:', error)
    ElMessage.error('获取课程类型失败')
  }
}

// 文件上传相关方法
const audioUploaded = ref(false)
const imageUploaded = ref(false)
const audioFile = ref(null)
const imageFile = ref(null)

const handleAudioChange = (file) => {
  audioFile.value = file.raw
  uploadAudioFile()
}

const handleImageChange = (file) => {
  imageFile.value = file.raw
  uploadImageFile()
}

const uploadAudioFile = async () => {
  if (!audioFile.value) return
  
  const formData = new FormData()
  formData.append('file', audioFile.value)
  
  try {
    const response = await axios.post('/admin/upload', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
    
    if (response.data.code === 200) {
      form2.value.filename = response.data.msg
      audioUploaded.value = true
      ElMessage.success('音频上传成功')
    } else {
      ElMessage.error('音频上传失败')
    }
  } catch (error) {
    console.error('音频上传失败:', error)
    ElMessage.error('音频上传失败')
  }
}

const uploadImageFile = async () => {
  if (!imageFile.value) return
  
  const formData = new FormData()
  formData.append('file', imageFile.value)
  
  try {
    const response = await axios.post('/admin/upload', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
    
    if (response.data.code === 200) {
      form2.value.img = response.data.msg
      imageUploaded.value = true
      ElMessage.success('图片上传成功')
    } else {
      ElMessage.error('图片上传失败')
    }
  } catch (error) {
    console.error('图片上传失败:', error)
    ElMessage.error('图片上传失败')
  }
}

const handleUploadError = (error) => {
  console.error('上传失败:', error)
  ElMessage.error('文件上传失败')
}

const beforeUpload = (file) => {
  const isAudio = file.type.startsWith('audio/')
  if (!isAudio) {
    ElMessage.error('只能上传音频文件!')
    return false
  }
  return true
}

const beforeUploadImg = (file) => {
  const isImage = file.type.startsWith('image/')
  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  return true
}

// 添加音频
const audioUploadRef = ref(null)
const imageUploadRef = ref(null)

const addFM = async () => {
  try {
    console.log('开始添加音频...')
    // 验证必填字段
    if (!form2.value.title) {
      ElMessage.error('请填写标题')
      return
    }
    
    // 检查是否已上传文件
    if (!audioUploaded.value && !form2.value.filename) {
      ElMessage.error('请选择音频文件')
      return
    }
    if (!imageUploaded.value && !form2.value.img) {
      ElMessage.error('请选择封面图片')
      return
    }
    
    // 构造请求参数
    const fmData = {
      title: form2.value.title,
      filename: form2.value.filename,
      img: form2.value.img,
      courseTypeId: form2.value.courseTypeId || null,
    }
    
    console.log('准备发送请求，数据:', fmData)
    
    // 调用后端添加接口
    const response = await axios.post('/admin/fm', fmData, {
      headers: {
        'Content-Type': 'application/json'
      }
    })
    
    console.log('收到响应:', response)
    
    if (response.data.code === 200) {
      ElMessage.success('添加成功')
      dialogFormVisible.value = false
      currentPage.value = 1  // 回到第一页
      getFMList()
      // 重置表单和上传状态
      form2.value = {
        title: "",
        filename: "",
        img: "",
        courseTypeId: "",
      }
      audioUploaded.value = false
      imageUploaded.value = false
      // 清空文件上传组件的状态
      if (audioUploadRef.value) {
        audioUploadRef.value.clearFiles()
      }
      if (imageUploadRef.value) {
        imageUploadRef.value.clearFiles()
      }
    } else {
      ElMessage.error(response.data.msg || '添加失败')
    }
  } catch (error) {
    console.error('添加失败，错误详情:', error)
    if (error.response) {
      console.error('错误响应:', error.response.data)
    }
    ElMessage.error('添加失败')
  }
}

// 修改音频
const EditFM = async () => {
  try {
    // 构造修改请求参数
    const updateData = {
      fmId: form2.value.fmId,
      title: form2.value.title,
      courseTypeId: form2.value.courseTypeId || null,
      filename: form2.value.filename,
      img: form2.value.img
    }

    // 验证必填字段
    if (!updateData.title) {
      ElMessage.error('请填写标题')
      return
    }

    // 调用修改接口
    const response = await axios.put(`admin/fm/${updateData.fmId}`, updateData)

    if (response.data.code === 200) {
      ElMessage.success('修改成功')
      xiugaiVisible.value = false
      getFMList()
      // 重置表单
      form2.value = {
        title: "",
        filename: "",
        img: "",
        courseTypeId: "",
      }
    } else {
      ElMessage.error(response.data.msg || '修改失败')
    }
  } catch (error) {
    console.error('修改失败:', error)
    ElMessage.error('修改失败')
  }
}

// 选中的行数据
const selectedRows = ref([])

// 表格选择事件处理
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

// 勾选删除
const deleteTick = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请先选择要删除的音频')
    return
  }

  try {
    // 确认删除
    await ElMessageBox.confirm(
      '确定要删除选中的音频吗？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )

    // 获取选中行的ID
    const ids = selectedRows.value.map(row => row.fmId)

    // 调用批量删除接口
    const response = await axios.delete('admin/fm/batch', {
      data: ids
    })

    if (response.data.code === 200) {
      ElMessage.success('删除成功')
      selectedRows.value = []
      getFMList()
    } else {
      ElMessage.error(response.data.msg || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 修改单个删除的方法
const handleDelete = async (id) => {
  try {
    // 确认删除
    await ElMessageBox.confirm(
      '确定要删除这条音频吗？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )

    const response = await axios.delete(`admin/fm/${id}`)
    if (response.data.code === 200) {
      ElMessage.success('删除成功')
      getFMList()
    } else {
      ElMessage.error(response.data.msg || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 编辑按钮点击事件
const handleEdit = (row) => {
  // 深拷贝行数据，避免直接修改表格数据
  form2.value = JSON.parse(JSON.stringify(row))
  xiugaiVisible.value = true
}

// 分页相关
const itemsArr = computed(() => fmList.value)

const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  getFMList()  // 重新获取数据
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  getFMList()  // 重新获取数据
}

// 搜索功能
const serchBtn = async () => {
  try {
    const response = await axios.get('admin/fm/list', {
      params: {
        id: searchCourseTypeId.value || null,
        title: searchTitle.value || null
      }
    })
    
    if (response.data.code === 200) {
      fmList.value = response.data.data
      total.value = response.data.data.length
    } else {
      ElMessage.error('搜索失败')
    }
  } catch (error) {
    console.error('搜索失败:', error)
    ElMessage.error('搜索失败')
  }
}

const resetSerchbtn = () => {
  searchTitle.value = ''
  searchCourseTypeId.value = ''
  getFMList()  // 重置后重新获取所有数据
}

// 获取课程类型名称
const getCourseTypeName = (id) => {
  const type = courseTypes.value.find(t => t.id === id)
  return type ? type.name : id
}

// 音频播放相关
const audioPlayerVisible = ref(false)
const audioPlayer = ref(null)
const currentAudio = ref({
  title: '',
  filename: ''
})

// 播放音频
const playAudio = (row) => {
  currentAudio.value = {
    title: row.title,
    filename: row.filename,
    img: row.img
  }
  audioPlayerVisible.value = true
  // 等待 DOM 更新后自动播放
  setTimeout(() => {
    if (audioPlayer.value) {
      audioPlayer.value.play()
      ElMessage.success('开始播放音频')
    }
  }, 100)
}

// 停止音频播放
const stopAudio = () => {
  if (audioPlayer.value) {
    audioPlayer.value.pause()
    audioPlayer.value.currentTime = 0
  }
}

// 监听对话框显示状态
watch(dialogFormVisible, async (newVal) => {
  if (newVal) {
    // 当对话框打开时，获取课程类型数据
    await getCourseTypes()
  }
})

// 组件挂载时获取数据
onMounted(() => {
  getFMList()
  getCourseTypes()
})

// 格式化日期时间
const formatDateTime = (dateTimeString) => {
  if (!dateTimeString) return ''
  const date = new Date(dateTimeString)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}
</script>

<style scoped>
.xitongYonghu{
  background-color: #cccccc;
}
.xitongYonghu-top{
  background-color: #cccccc;
}
.xitongYonghu {
  width: 100%;
  background-color: #cccccc;
  padding: 15px;
}

.xitongYonghu li {
  width: 100%;
  border-radius: 5px;
}

.xitongYonghu-top {
  background-color: transparent;
  margin-bottom: 10px;
}

.el-pagination {
  margin-top: 10px;
}

.upload-demo {
  margin-bottom: 10px;
}

.operation-group {
  display: flex;
  align-items: center;
  width: 100%;
}

.operation-group .el-button {
  display: flex;
  align-items: center;
  gap: 5px;
  margin-right: 10px;
}

.operation-group input {
  margin: 0 10px;
  height: 32px;
  width: 250px;
  box-sizing: border-box;
  padding: 5px 10px;
  border-radius: 5px;
  border: none;
}

.operation-buttons {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.operation-buttons .el-button {
  padding: 5px 10px;
  min-width: 40px;
}

:deep(.el-table) {
  width: 100% !important;
  margin: 0;
  padding: 0;
}

:deep(.el-table__fixed-right) {
  height: 100% !important;
  right: 0;
}

.avatar-uploader {
  text-align: center;
}

.avatar-wrapper {
  position: relative;
  display: inline-block;
}

.avatar-uploader .avatar {
  width: 200px;
  height: 200px;
  display: block;
  object-fit: cover;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
}

.avatar-uploader .avatar-uploader-icon {
  width: 200px;
  height: 200px;
  font-size: 28px;
  color: #8c939d;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
  display: flex;
  align-items: center;
  justify-content: center;
}

.avatar-uploader .avatar-uploader-icon:hover {
  border-color: var(--el-color-primary);
  color: var(--el-color-primary);
}

.upload-tip {
  font-size: 12px;
  color: #666;
  margin-top: 8px;
  line-height: 1.5;
}

.audio-player-container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  gap: 12px;
}

.audio-info {
  text-align: center;
}

.audio-cover {
  width: 150px;
  height: 150px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.audio-player-container audio {
  width: 100%;
  outline: none;
  border-radius: 8px;
}

/* 自定义音频控件样式 */
.audio-player-container audio::-webkit-media-controls-panel {
  background-color: #f5f7fa;
  border-radius: 8px;
}

.audio-player-container audio::-webkit-media-controls-play-button {
  background-color: #409eff;
  border-radius: 50%;
}

.audio-player-container audio::-webkit-media-controls-current-time-display,
.audio-player-container audio::-webkit-media-controls-time-remaining-display {
  color: #606266;
}

.audio-dialog :deep(.el-dialog) {
  min-width: 350px;
}

.audio-dialog :deep(.el-dialog__header) {
  padding: 12px;
  margin: 0;
  border-bottom: 1px solid #eee;
}

.audio-dialog :deep(.el-dialog__body) {
  padding: 15px;
}

.audio-dialog :deep(.el-dialog__title) {
  font-size: 16px;
}

.search-group {
  display: flex;
  align-items: center;
  gap: 10px;
}

.search-group .el-select {
  width: 150px;
}
</style> 